package com.ssy.wireless.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * Created by cofey on 16/11/20.
 */
public class WebUserSecurityInterceptor implements HandlerInterceptor {
    private final static String[] ignores = {"/login", "/logout", "/assets", "/error", "/api", "/swagger-resources"};

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String url = requestUri.substring(contextPath.length());
        long position = 1;
        if (!url.equals("/")) {
            position = Arrays.stream(ignores).filter(str -> url.indexOf(str) >= 0).count();
        }
        //暂时从上下文中获取
        Object object = request.getSession().getAttribute("currUser");
        if (object == null && position < 1) {
            response.sendRedirect(contextPath);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}
